'use strict';

const { Service } = require('ee-core');
const path = require('path');
const Services = require('ee-core/services');
const fs = require('fs'); 
const Ps = require('ee-core/ps');
const CoreWindow = require('ee-core/electron/window');
const Conf = require('ee-core/config');

const cfg = Conf.getValue('main');
let DOWNLOAD_RES = 'caches';
let mainPath = cfg.mainPath;
var extraPath = Ps.getExtraResourcesDir();
let GUI = 'GUI';
let extraGUI = path.resolve(extraPath, GUI);
const CONFIG_PATH = path.resolve(mainPath, 'config.json');
let mainGUI = path.resolve(mainPath, GUI);

/**
 * 节目
 * @class
 */
class ProgramService extends Service {


  constructor(ctx) {
    super(ctx);
	this.downloadQueue = [];
	this.download = false;
  }

  
  // 递归创建目录
  mkdirRecursive(dirname) {
    // 判断是否存在当前 path 的最后一层目录
    if (fs.existsSync(dirname)) 
        // 存在，则不做操作，直接返回
        return true
    
    // 若不存在，则判断当前 path 倒数第二层目录是否存在
    // path.dirname 可以获取当前路径的上一层路径
    // 例如： /dirName1/dirName2/dirName3
    // path.dirname('/dirName1/dirName2/dirName3') // /dirName1/dirName2
    if (this.mkdirRecursive(path.dirname(dirname))) {
        // 若存在，则在当前目录，创建下一层目录
        fs.mkdirSync(dirname)
        return true
    }
  }
  /** 按顺序下载
   * @param {String} jsonData 节目内容
   * @param {String} pubId 发布ID
   */
  async downloadByOrder(jsonData, pubId) {
	if (this.download) {
		this.downloadQueue.push({jsonData: jsonData, pubId: pubId});
	} else {
		this.download = true;
		await this.parseProgram(jsonData, pubId);
	}
  }

  
  /**解析节目
   * @param {String} jsonData 节目内容
   * @param {String} pubId 发布ID
   */
  async parseProgram(jsonData, pubId, isLocal = false) {
    // var exePath = path.dirname(app.getPath('exe'));
    // 检查文件夹是否存在
    if (!fs.existsSync(mainGUI)) {
      // 不存在则拷贝
      this.copyDirectory(extraGUI, mainGUI);
    }
    let dirname = mainGUI;
    dirname = path.resolve(dirname, DOWNLOAD_RES);

    let cachesDir = dirname;
    dirname = path.resolve(dirname, pubId);
    this.mkdirRecursive(dirname)
    let templatePath = path.resolve(dirname, 'template.json');

    // 校验是否正在下载... 不包含则添加
    if(!this.checkDownloadingPubId(pubId)) {
      this.addDownloadingPubId(pubId);
      fs.writeFileSync(templatePath, jsonData);
    } else {
      if (!isLocal) return;
    }
    if (!jsonData) {
      jsonData = fs.readFileSync(templatePath, 'utf-8');
    }
    
    // 上传正在更新状态
    Services.get('api').uploadProgramStatus(pubId, "2");

    let jProgram = JSON.parse(jsonData);
    if (jProgram.background){
      const fileName = path.basename(jProgram.background);
      let fullPath = path.resolve(dirname, fileName);
      let res = await Services.get('download').downloadFast(jProgram.background, fullPath);
      
      if (res) {
		fullPath = fullPath.replace(mainGUI, '');
		fullPath = fullPath.replace(/\\/g, '/');
		fullPath = '.' + fullPath;
        jProgram.background = fullPath;
      } else {
        // 下载失败
        jProgram.background = '';
      }
    }
    // 遍历areas
    for (let i = 0; i < jProgram.areas.length; i++) {
      let area = jProgram.areas[i];
      // 视频和图片控件进行下载
      if (area.type == 'slider' || area.type == 'video') {
        // 遍历urls对象列表
        for (let j = 0; j < area.urls.length; j++) {
          let urlObj = area.urls[j];
          if (urlObj.url) {
            const fileName = path.basename(urlObj.url);
            let fullPath = path.resolve(dirname, fileName);
            let res = await Services.get('download').downloadFast(urlObj.url, fullPath);
            if (res) {
			  fullPath = fullPath.replace(mainGUI, '');
			  fullPath = fullPath.replace(/\\/g, '/');
			  fullPath = '.' + fullPath;
              jProgram.areas[i].urls[j].url = fullPath;
            } else{
              // 下载失败
              jProgram.areas[i].urls[j].url = '';
            }
          }
        }
      }
    }
    // 下载完成
    this.removeDownloadingPubId(pubId);

    Services.get('api').uploadProgramStatus(pubId, "0");

    // 将JSON转成字符串写到template.json
    let programJsonstr = JSON.stringify(jProgram, null, 2);
    fs.writeFileSync(templatePath, programJsonstr);


    // GUI
    let htmlTemplatePath = mainGUI;
    let htmlPath = path.resolve(htmlTemplatePath, 'index.html');
    htmlTemplatePath = path.resolve(htmlTemplatePath, 'html.template');
    // 讀取html.template文件
    if (fs.existsSync(htmlTemplatePath)) {
      let jBody = {};
      jBody.body = {};
      jBody.body.templatejson = jProgram;
      let templateJsonStr = JSON.stringify(jBody, null, 2);
      let htmlTemplate = fs.readFileSync(htmlTemplatePath, 'utf-8');
      htmlTemplate = htmlTemplate.replace('%HTML_TEMPLATE_CONTENT%', templateJsonStr);
      fs.writeFileSync(htmlPath, htmlTemplate);
    }

    // 此处通知播放器重新加载
    this.sendStatusToWindow();

	const that = this;
	// 延迟5秒删除
	setTimeout(function() {
		// 将template.json文件路径写入配置文件
		let config = that.readConfig();
		if (config) {
		  config.template = templatePath;
		  that.deleteLastPub(cachesDir, config.pubId);
		  config.pubId = pubId;
		} else {
		  config = {
			template: templatePath,
			pubId: pubId
		  }
		}
		that.writeConfig(config);
		// 看下载队列是否有数据
		if (that.downloadQueue.length > 0) {
			that.parseProgram(that.downloadQueue[0].jsonData, that.downloadQueue[0].pubId);
			that.downloadQueue.shift();
		} else {
			that.download = false;
		}
	}, 5 * 1000);

  }

  /**
   * 添加正在下载的发布ID
   * @param {String} pubId 
   */
  addDownloadingPubId(pubId) {
    let config = this.readConfig();
    if (config) {
      if (config.downloadingPubIds) {
        config.downloadingPubIds.push(pubId);
      } else {
        config.downloadingPubIds = [pubId];
      }
    } else {
      config = {
        downloadingPubIds: [pubId]
      }
    }
    this.writeConfig(config);
  }

  
  /**
   * 移除正在下载的发布ID（下载完成后调用）
   * @param {String} pubId 
   */
  removeDownloadingPubId(pubId) {
    let config = this.readConfig();
    if (config) {
      if (config.downloadingPubIds) {
        for (let i = 0; i < config.downloadingPubIds.length; i++) {
          if (config.downloadingPubIds[i] == pubId) {
            config.downloadingPubIds.splice(i, 1);
            break;
          }
        }
      } 
    }
    this.writeConfig(config);
  }


  
  /**
   * 获取正在下载的发布ID
   * @returns {Array}
   */
  getDownloadingPubIds() {
    let config = this.readConfig();
    if (config && config.downloadingPubIds) {
      return config.downloadingPubIds;
    }
    return [];
  }

  /**
   * 校验发布ID是否正在下载
   * @param {String} pubId 
   * @returns 
   */
  checkDownloadingPubId(pubId) {
    let arrPubIds = this.getDownloadingPubIds();
    for (let i = 0; i < arrPubIds.length; i++) {
      if (arrPubIds[i] == pubId) {
        return true;
      }
    }
    return false;
  }


  /**
   * 读取config.json配置文件
   * @returns 
   */
  readConfig() {
    let config = null;
    if (fs.existsSync(CONFIG_PATH)) {
      config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
    }
    return config;
  }

  /**
   * 写入配置文件
   * @param {JSON} config 
   */
  writeConfig(config) {
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
  }

  // 检查节目是否下载完成 未下载完成接着下载
  checkLocalProgram() {
    let arrPubIds = this.getDownloadingPubIds();
    for (let i = 0; i < arrPubIds.length; i++) {
      this.parseProgram(null, arrPubIds[i], true);
    }
  }



  // 根据发布ID删除下载的素材内容
  deleteLastPub(cachesDir, pubId) {
    if (cachesDir && pubId) {
      let dirname = path.resolve(cachesDir, pubId);
      if (fs.existsSync(dirname)) {
        this.deleteFolderRecursively(dirname);
      }
    }
  }

  /**
   * 递归删除文件夹及下面的文件
   * @param {String} dir 
   */
  deleteFolderRecursively(dir) {
    if (fs.existsSync(dir)) {
      fs.readdirSync(dir).forEach(function (file, index) {
        let curPath = path.join(dir, file);
        if (fs.lstatSync(curPath).isDirectory()) { // recurse
          this.deleteFolderRecursively(curPath);
        } else { 
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(dir);
    }
  }

  /**
   * 循环遍历拷贝文件夹
   * @param {string} sourcePath 
   * @param {string} destinationPath 
   */
  copyDirectory(sourcePath, destinationPath) {
    // 读取源路径下的所有文件和子目录
    const filesAndFolders = fs.readdirSync(sourcePath);
    
    // 创建目标路径（如果不存在）
    if (!fs.existsSync(destinationPath)) {
        fs.mkdirSync(destinationPath);
    }
    
    // 遍历每个文件或者子目录
    for (let i = 0; i < filesAndFolders.length; i++) {
        const fileOrFolderName = filesAndFolders[i];
        
        // 构造完整的源路径和目标路径
        const sourceFilePath = path.join(sourcePath, fileOrFolderName);
        const destinationFilePath = path.join(destinationPath, fileOrFolderName);
        
        // 判断当前项是否为文件
        if (fs.statSync(sourceFilePath).isFile()) {
            // 如果是文件则直接复制到目标路径
            fs.copyFileSync(sourceFilePath, destinationFilePath);
        } else {
            // 如果是文件夹则递归调用自身进行复制
            this.copyDirectory(sourceFilePath, destinationFilePath);
        }
    }
}

    /**
   * 向前端发消息
   */
    sendStatusToWindow(content = {}) {
      const textJson = JSON.stringify(content);
      const channel = 'program.downloaded';
      const win = CoreWindow.getMainWindow();
      win.webContents.send(channel, textJson);
    }

}

ProgramService.toString = () => '[class ProgramService]';
module.exports = ProgramService;  